import React, { useState, useEffect } from "react";
import { 
  Card, 
  Form, 
  Input, 
  Button, 
  Row, 
  Col, 
  message, 
  Steps, 
  Select, 
  DatePicker, 
  TimePicker, 
  Checkbox, 
  Transfer, 
  Modal, 
  Progress,
  Tag,
  Divider,
  Space,
  Typography,
  Alert,
  Result,
  Spin
} from "antd";
import { 
  PlusOutlined, 
  TeamOutlined, 
  CalendarOutlined, 
  CheckCircleOutlined,
  ArrowRightOutlined,
  UserOutlined,
  BookOutlined,
  SettingOutlined
} from "@ant-design/icons";
import { useNavigate } from "react-router-dom";
import dayjs from "dayjs";
import ENV_CONFIG from "../../../config/env";
import { CLASSES } from "../../../utils/mockData";

const { Step } = Steps;
const { Option } = Select;
const { TextArea } = Input;
const { Title, Text } = Typography;

interface CourseFormData {
  // 基本信息
  name: string;
  code: string;
  description: string;
  category: string;
  credits: number;
  hours: number;
  
  // 时间安排
  semester: string;
  schedule: any[];
  location: string;
  
  // 班级选择
  selectedClasses: string[];
  maxStudents: number;
  
  // 其他设置
  status: string;
  allowAudit: boolean;
  requireApproval: boolean;
}

interface ClassData {
  id: string;
  name: string;
  code: string;
  grade: string;
  major: string;
  studentCount: number;
}

const AddCourse: React.FC = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();

  // 步骤控制
  const [currentStep, setCurrentStep] = useState(0);
  const [stepLoading, setStepLoading] = useState(false);
  
  // AI建议
  const [aiSuggestion, setAiSuggestion] = useState<string>("");
  const [aiLoading, setAiLoading] = useState(false);
  
  // 提交状态
  const [submitting, setSubmitting] = useState(false);
  const [submitSuccess, setSubmitSuccess] = useState(false);
  const [courseId, setCourseId] = useState<string>("");
  
  // 数据
  const [availableClasses, setAvailableClasses] = useState<ClassData[]>([]);
  const [selectedClassDetails, setSelectedClassDetails] = useState<ClassData[]>([]);
  
  // 使用统一的班级数据
  useEffect(() => {
    const classData: ClassData[] = CLASSES.map(cls => ({
      id: cls.id,
      name: cls.name,
      code: cls.code,
      grade: cls.grade,
      major: cls.major,
      studentCount: cls.studentCount
    }));
    setAvailableClasses(classData);
  }, []);

  // 获取AI建议
  const handleAISuggestion = async () => {
    try {
      const values = await form.validateFields();
      setAiLoading(true);
      setAiSuggestion("");
      
      const resp = await fetch(`${ENV_CONFIG.AI_API_BASE_URL}/api/teach/course-suggestion`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          course_name: values.name || "",
          course_code: values.code || "",
          schedule: values.schedule || "",
          location: values.location || "",
          description: values.description || "",
        }),
      });
      
      const data = await resp.json();
      if (data.code === 0 && data.data) {
        setAiSuggestion(data.data);
      } else {
        setAiSuggestion("");
        message.error(data.msg || "AI建议获取失败");
      }
    } catch (err) {
      console.error("AI建议请求失败:", err);
      setAiSuggestion("");
      message.error("请先填写完整课程信息或检查网络连接");
    } finally {
      setAiLoading(false);
    }
  };

  // 下一步
  const handleNext = async () => {
    try {
      setStepLoading(true);
      await form.validateFields();
      
      // 根据当前步骤进行验证
      if (currentStep === 0) {
        // 基本信息验证通过
        setCurrentStep(1);
      } else if (currentStep === 1) {
        // 时间安排验证通过
        setCurrentStep(2);
      } else if (currentStep === 2) {
        // 班级选择验证通过
        setCurrentStep(3);
      }
    } catch (error) {
      console.error("表单验证失败:", error);
    } finally {
      setStepLoading(false);
    }
  };

  // 上一步
  const handlePrev = () => {
    setCurrentStep(currentStep - 1);
  };

  // 班级选择变化
  const handleClassChange = (targetKeys: React.Key[]) => {
    const selectedClasses = availableClasses.filter(cls => targetKeys.includes(cls.id));
    setSelectedClassDetails(selectedClasses);
    form.setFieldsValue({ selectedClasses: targetKeys });
  };

  // 提交课程
  const handleSubmit = async (values: CourseFormData) => {
    try {
      setSubmitting(true);
      
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      // 生成课程ID
      const newCourseId = `course_${Date.now()}`;
      setCourseId(newCourseId);
      
      // 模拟成功响应
      console.log("课程创建成功:", {
        ...values,
        id: newCourseId,
        createTime: new Date().toISOString(),
        status: "active"
      });
      
      setSubmitSuccess(true);
      message.success("课程创建成功！");
      
    } catch (error) {
      console.error("创建课程失败:", error);
      message.error("创建课程失败，请重试");
    } finally {
      setSubmitting(false);
    }
  };

  // 完成后的操作
  const handleFinish = () => {
    navigate("/teacher/courses");
  };

  // 查看课程详情
  const handleViewCourse = () => {
    navigate(`/teacher/courses/${courseId}`);
  };

  // 继续创建课程
  const handleCreateAnother = () => {
    setSubmitSuccess(false);
    setCurrentStep(0);
    form.resetFields();
    setSelectedClassDetails([]);
  };

  const steps = [
    {
      title: "基本信息",
      icon: <BookOutlined />,
      description: "填写课程基本信息"
    },
    {
      title: "时间安排",
      icon: <CalendarOutlined />,
      description: "设置上课时间和地点"
    },
    {
      title: "班级选择",
      icon: <TeamOutlined />,
      description: "选择授课班级"
    },
    {
      title: "完成创建",
      icon: <CheckCircleOutlined />,
      description: "确认并创建课程"
    }
  ];

  // 渲染基本信息步骤
  const renderBasicInfo = () => (
    <div>
      <Alert
        message="课程基本信息"
        description="请填写课程的基本信息，包括课程名称、代码、描述等。这些信息将用于课程管理和学生选课。"
        type="info"
        showIcon
        style={{ marginBottom: 24 }}
      />
      
      <Row gutter={16}>
        <Col span={12}>
          <Form.Item
            name="name"
            label="课程名称"
            rules={[{ required: true, message: "请输入课程名称" }]}
          >
            <Input placeholder="请输入课程名称" />
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            name="code"
            label="课程代码"
            rules={[{ required: true, message: "请输入课程代码" }]}
          >
            <Input placeholder="如：CS101" />
          </Form.Item>
        </Col>
      </Row>

      <Row gutter={16}>
        <Col span={12}>
          <Form.Item
            name="category"
            label="课程类别"
            rules={[{ required: true, message: "请选择课程类别" }]}
          >
            <Select placeholder="请选择课程类别">
              <Option value="必修">必修课</Option>
              <Option value="选修">选修课</Option>
              <Option value="公共课">公共课</Option>
              <Option value="专业课">专业课</Option>
            </Select>
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            name="credits"
            label="学分"
            rules={[{ required: true, message: "请输入学分" }]}
          >
            <Select placeholder="请选择学分">
              <Option value={1}>1学分</Option>
              <Option value={2}>2学分</Option>
              <Option value={3}>3学分</Option>
              <Option value={4}>4学分</Option>
              <Option value={5}>5学分</Option>
            </Select>
          </Form.Item>
        </Col>
      </Row>

      <Row gutter={16}>
        <Col span={12}>
          <Form.Item
            name="hours"
            label="学时"
            rules={[{ required: true, message: "请输入学时" }]}
          >
            <Select placeholder="请选择学时">
              <Option value={16}>16学时</Option>
              <Option value={32}>32学时</Option>
              <Option value={48}>48学时</Option>
              <Option value={64}>64学时</Option>
              <Option value={80}>80学时</Option>
            </Select>
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            name="maxStudents"
            label="最大学生数"
            rules={[{ required: true, message: "请输入最大学生数" }]}
          >
            <Select placeholder="请选择最大学生数">
              <Option value={30}>30人</Option>
              <Option value={50}>50人</Option>
              <Option value={80}>80人</Option>
              <Option value={100}>100人</Option>
              <Option value={150}>150人</Option>
            </Select>
          </Form.Item>
        </Col>
      </Row>

      <Form.Item
        name="description"
        label="课程描述"
        rules={[{ required: true, message: "请输入课程描述" }]}
      >
        <TextArea 
          rows={4} 
          placeholder="请详细描述课程内容、教学目标、考核方式等"
          maxLength={500}
          showCount
        />
      </Form.Item>
    </div>
  );

  // 渲染时间安排步骤
  const renderSchedule = () => (
    <div>
      <Alert
        message="时间安排设置"
        description="请设置课程的开课学期、上课时间和地点。支持多个时间段设置。"
        type="info"
        showIcon
        style={{ marginBottom: 24 }}
      />
      
      <Row gutter={16}>
        <Col span={12}>
          <Form.Item
            name="semester"
            label="开课学期"
            rules={[{ required: true, message: "请选择开课学期" }]}
          >
            <Select placeholder="请选择学期">
              <Option value="2024春季">2024春季</Option>
              <Option value="2024夏季">2024夏季</Option>
              <Option value="2024秋季">2024秋季</Option>
              <Option value="2024冬季">2024冬季</Option>
            </Select>
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            name="location"
            label="上课地点"
            rules={[{ required: true, message: "请输入上课地点" }]}
          >
            <Input placeholder="如：教学楼A101" />
          </Form.Item>
        </Col>
      </Row>

      <Form.Item
        name="schedule"
        label="上课时间"
        rules={[{ required: true, message: "请设置上课时间" }]}
      >
        <div>
          <div style={{ marginBottom: 16 }}>
            <Text type="secondary">请选择上课的星期和时间段</Text>
          </div>
          <Row gutter={16}>
            <Col span={8}>
              <Select placeholder="星期" style={{ width: '100%' }}>
                <Option value="monday">星期一</Option>
                <Option value="tuesday">星期二</Option>
                <Option value="wednesday">星期三</Option>
                <Option value="thursday">星期四</Option>
                <Option value="friday">星期五</Option>
                <Option value="saturday">星期六</Option>
                <Option value="sunday">星期日</Option>
              </Select>
            </Col>
            <Col span={8}>
              <Select placeholder="节次" style={{ width: '100%' }}>
                <Option value="1-2">第1-2节 (8:00-9:40)</Option>
                <Option value="3-4">第3-4节 (10:00-11:40)</Option>
                <Option value="5-6">第5-6节 (14:00-15:40)</Option>
                <Option value="7-8">第7-8节 (16:00-17:40)</Option>
                <Option value="9-10">第9-10节 (19:00-20:40)</Option>
              </Select>
            </Col>
            <Col span={8}>
              <Button type="dashed" icon={<PlusOutlined />}>
                添加时间段
              </Button>
            </Col>
          </Row>
        </div>
      </Form.Item>
    </div>
  );

  // 渲染班级选择步骤
  const renderClassSelection = () => (
    <div>
      <Alert
        message="班级选择"
        description="请选择要授课的班级。系统会自动计算总学生数，确保不超过课程容量。"
        type="info"
        showIcon
        style={{ marginBottom: 24 }}
      />
      
      <Form.Item
        name="selectedClasses"
        label="选择班级"
        rules={[{ required: true, message: "请至少选择一个班级" }]}
      >
        <Transfer
          dataSource={availableClasses.map(cls => ({
            key: cls.id,
            title: `${cls.name} (${cls.code})`,
            description: `${cls.grade}级 ${cls.major} - ${cls.studentCount}人`,
          }))}
          targetKeys={selectedClassDetails.map(cls => cls.id)}
          onChange={handleClassChange}
          render={item => item.title}
          showSearch
          listStyle={{
            width: 300,
            height: 400,
          }}
          titles={['可选班级', '已选班级']}
        />
      </Form.Item>

      {selectedClassDetails.length > 0 && (
        <div style={{ marginTop: 16 }}>
          <Title level={5}>已选班级详情</Title>
          <Row gutter={16}>
            {selectedClassDetails.map(cls => (
              <Col span={8} key={cls.id}>
                <Card size="small" style={{ marginBottom: 8 }}>
                  <div>
                    <Text strong>{cls.name}</Text>
                    <br />
                    <Text type="secondary">{cls.code}</Text>
                    <br />
                    <Tag color="blue">{cls.studentCount}人</Tag>
                  </div>
                </Card>
              </Col>
            ))}
          </Row>
          <Divider />
          <div>
            <Text strong>总学生数：</Text>
            <Text type="danger" style={{ fontSize: 16, marginLeft: 8 }}>
              {selectedClassDetails.reduce((sum, cls) => sum + cls.studentCount, 0)}人
            </Text>
          </div>
        </div>
      )}
    </div>
  );

  // 渲染确认步骤
  const renderConfirmation = () => {
    const values = form.getFieldsValue();
    const totalStudents = selectedClassDetails.reduce((sum, cls) => sum + cls.studentCount, 0);
    
    return (
      <div>
        <Alert
          message="确认课程信息"
          description="请确认以下课程信息无误，提交后将创建课程。"
          type="warning"
          showIcon
          style={{ marginBottom: 24 }}
        />
        
        <Card title="课程基本信息" style={{ marginBottom: 16 }}>
          <Row gutter={16}>
            <Col span={12}>
              <Text strong>课程名称：</Text>
              <Text>{values.name}</Text>
            </Col>
            <Col span={12}>
              <Text strong>课程代码：</Text>
              <Text>{values.code}</Text>
            </Col>
          </Row>
          <Row gutter={16} style={{ marginTop: 8 }}>
            <Col span={12}>
              <Text strong>课程类别：</Text>
              <Tag color="blue">{values.category}</Tag>
            </Col>
            <Col span={12}>
              <Text strong>学分：</Text>
              <Text>{values.credits}学分</Text>
            </Col>
          </Row>
          <Row style={{ marginTop: 8 }}>
            <Col span={24}>
              <Text strong>课程描述：</Text>
              <Text>{values.description}</Text>
            </Col>
          </Row>
        </Card>

        <Card title="时间安排" style={{ marginBottom: 16 }}>
          <Row gutter={16}>
            <Col span={12}>
              <Text strong>开课学期：</Text>
              <Text>{values.semester}</Text>
            </Col>
            <Col span={12}>
              <Text strong>上课地点：</Text>
              <Text>{values.location}</Text>
            </Col>
          </Row>
        </Card>

        <Card title="班级信息" style={{ marginBottom: 16 }}>
          <Row gutter={16}>
            <Col span={12}>
              <Text strong>已选班级：</Text>
              <Text>{selectedClassDetails.length}个</Text>
            </Col>
            <Col span={12}>
              <Text strong>总学生数：</Text>
              <Text type="danger">{totalStudents}人</Text>
            </Col>
          </Row>
          <div style={{ marginTop: 8 }}>
            {selectedClassDetails.map(cls => (
              <Tag key={cls.id} color="green" style={{ marginBottom: 4 }}>
                {cls.name} ({cls.studentCount}人)
              </Tag>
            ))}
          </div>
        </Card>

        <Form.Item
          name="status"
          label="课程状态"
          rules={[{ required: true, message: "请选择课程状态" }]}
        >
          <Select placeholder="请选择课程状态">
            <Option value="active">立即开始</Option>
            <Option value="inactive">暂不开始</Option>
          </Select>
        </Form.Item>

        <Form.Item name="allowAudit" valuePropName="checked">
          <Checkbox>允许旁听</Checkbox>
        </Form.Item>

        <Form.Item name="requireApproval" valuePropName="checked">
          <Checkbox>需要学生选课审批</Checkbox>
        </Form.Item>
      </div>
    );
  };

  // 渲染成功页面
  const renderSuccess = () => (
    <Result
      status="success"
      title="课程创建成功！"
      subTitle={`课程ID: ${courseId}`}
      extra={[
        <Button type="primary" key="view" onClick={handleViewCourse}>
          查看课程详情
        </Button>,
        <Button key="create" onClick={handleCreateAnother}>
          继续创建课程
        </Button>,
        <Button key="finish" onClick={handleFinish}>
          返回课程列表
        </Button>,
      ]}
    />
  );

  if (submitSuccess) {
    return renderSuccess();
  }

  return (
    <div style={{ padding: 24 }}>
      <Card>
        <Steps current={currentStep} items={steps} style={{ marginBottom: 32 }} />
        
        <Row gutter={24}>
          <Col span={16}>
            <Form
              form={form}
              layout="vertical"
              onFinish={handleSubmit}
              initialValues={{
                status: "active",
                allowAudit: false,
                requireApproval: false,
              }}
            >
              {currentStep === 0 && renderBasicInfo()}
              {currentStep === 1 && renderSchedule()}
              {currentStep === 2 && renderClassSelection()}
              {currentStep === 3 && renderConfirmation()}

              <div style={{ marginTop: 24, textAlign: 'right' }}>
                <Space>
                  {currentStep > 0 && (
                    <Button onClick={handlePrev}>
                      上一步
                    </Button>
                  )}
                  {currentStep < steps.length - 1 && (
                    <Button 
                      type="primary" 
                      onClick={handleNext}
                      loading={stepLoading}
                    >
                      下一步
                      <ArrowRightOutlined />
                    </Button>
                  )}
                  {currentStep === steps.length - 1 && (
                    <Button 
                      type="primary" 
                      htmlType="submit"
                      loading={submitting}
                      icon={<CheckCircleOutlined />}
                    >
                      创建课程
                    </Button>
                  )}
                </Space>
              </div>
            </Form>
          </Col>
          
          <Col span={8}>
            <Card
              title="AI建议"
              extra={
                <Button 
                  onClick={handleAISuggestion} 
                  loading={aiLoading} 
                  type="primary"
                  size="small"
                >
                  获取建议
                </Button>
              }
            >
              <div style={{ minHeight: 200, whiteSpace: 'pre-wrap' }}>
                {aiSuggestion ? (
                  <div>
                    <Text strong>AI建议：</Text>
                    <div style={{ marginTop: 8 }}>
                      {aiSuggestion}
                    </div>
                  </div>
                ) : (
                  <div style={{ textAlign: 'center', color: '#999' }}>
                    <BookOutlined style={{ fontSize: 24, marginBottom: 8 }} />
                    <br />
                    点击右上角获取AI建议
                  </div>
                )}
              </div>
            </Card>

            {currentStep > 0 && (
              <Card title="创建进度" style={{ marginTop: 16 }}>
                <Progress 
                  percent={(currentStep / (steps.length - 1)) * 100} 
                  status="active"
                />
                <div style={{ marginTop: 8 }}>
                  <Text type="secondary">
                    已完成 {currentStep}/{steps.length - 1} 步
                  </Text>
                </div>
              </Card>
            )}
          </Col>
        </Row>
      </Card>
    </div>
  );
};

export default AddCourse;
